package Controller

import (
	"backend/Dao"
	"backend/Service/dbService"
	"backend/Service/redisService"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"strconv"
)

type LoginController struct{}
type Login struct {
	UserName string
	Password string
	Rem      bool
}
type LoginRes struct {
	Token       string
	TeacherName string
	TeacherAva  string
}
type StuLoginRes struct {
	Token       string
	StudentName string
	StudentAva  string
}

//
// TeacherLogin
// @Description: 教师登陆
// @author MaTaoXun 2022-01-15 17:30:06
// @return gin.HandlerFunc
//
func (this LoginController) TeacherLogin(c *gin.Context) {
	var data = Login{}
	err := c.BindJSON(&data)
	if err != nil {
		fmt.Println("TeacherLoginerr", err)
	}
	var teacher = &Dao.Teacher{}
	dbService.DbConn.Where("teacher_username = ?", data.UserName).Find(&teacher)
	fmt.Println(teacher, data)
	if teacher.TeacherUsername == "" {
		c.String(401, "无此用户")
	} else if teacher.TeacherPwd == data.Password {
		s := uuid.New().String()
		token := redisService.SetToken(strconv.Itoa(int(teacher.Model.ID)), data.Rem, "t-"+s)
		c.JSON(200, LoginRes{
			Token:       token,
			TeacherName: teacher.TeacherName,
			TeacherAva:  teacher.TeacherAva,
		})
	} else {
		c.String(401, "密码错误")
	}
}

//
// StudentLogin
// @Description: 学生登陆
// @author MaTaoXun 2022-01-15 17:30:14
// @return gin.HandlerFunc
//
func (this LoginController) StudentLogin(c *gin.Context) {
	var data = Login{}
	err := c.BindJSON(&data)
	if err != nil {
		fmt.Println("TeacherLoginerr", err)
	}
	var student = &Dao.Student{}
	dbService.DbConn.Where("stu_num = ?", data.UserName).Find(&student)
	fmt.Println(student, data)
	if student.StuNum == "" {
		c.String(401, "无此用户")
	} else if student.StuPwd == data.Password {
		token := redisService.SetToken(strconv.Itoa(int(student.Model.ID)), data.Rem, uuid.New().String())
		c.JSON(200, StuLoginRes{
			Token:       token,
			StudentName: student.StuName,
			StudentAva:  student.StuAva,
		})
	} else {
		c.String(401, "密码错误")
	}
}

type reqCheckLogStatus struct {
	Token string
}

//
// CheckLogStatus
// @Description: 检查登陆状态
// @author MaTaoXun 2022-01-15 17:29:12
// @return gin.HandlerFunc
//
func (this LoginController) CheckLogStatus(c *gin.Context) {
	var data = reqCheckLogStatus{}
	err := c.BindJSON(&data)
	if err != nil {
		fmt.Println("StudentLoginerr", err)
	}
	token, _ := redisService.GetIdByToken(data.Token)
	if !token {
		c.String(401, "noLog")
	} else {
		c.String(200, "Loged")
	}
}
